package com.lvtulife.common.web.util;

import com.lvtulife.common.web.component.onekeyBuild.FieldColumn;
import org.apache.commons.lang3.StringUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @作者：liujiancheng
 * @方法描述：解析实体类配置XML
 * @创建时间: 2014-8-26 下午12:03:18
 */
public class JdomPojoXmlUtil {
    private static Logger logger = LoggerFactory.getLogger(JdomPojoXmlUtil.class);
    private String mainXMLPath = "/mybatis/pojoFieldColumn-config.xml";
    private String ibatisXmlPath;
    private Document mainDoc;
    private Document doc;
    private URL mainUrl;
    private URL url;
    private String type;
    XMLOutputter out = new XMLOutputter();

    /**
     * @param ibatisPojoName 实体类名称
     * @param type           hibernate/ibatis
     */
    public JdomPojoXmlUtil(String ibatisPojoName, String type) {
        try {
            InputStream is = JdomXML.class.getResourceAsStream(mainXMLPath);
            this.mainDoc = new SAXBuilder().build(is);
            Element root = this.mainDoc.getRootElement();
            this.ibatisXmlPath = getIbatisXmlPath(root, ibatisPojoName, type);
        } catch (Exception e) {
            logger.error("配置文件读取异常！", e);
        }
    }

    /**
     * 获得实体类XML路径
     *
     * @param pojoName 实体类名称
     * @return
     */
    public String getIbatisXmlPath(Element root, String pojoName, String type) {
        Element pojoElement;
        if (StringUtils.isBlank(type))
            type = "hibernate";
        this.type = type;
        if (type.equals("hibernate")) {
            Element hibernatePojoElement = root.getChild("hibernatePojo");
            if (hibernatePojoElement == null) {
                return null;
            }
            pojoElement = hibernatePojoElement.getChild(pojoName);
        } else {
            Element ibatisPojoElement = root.getChild("ibatisPojo");
            if (ibatisPojoElement == null) {
                return null;
            }
            pojoElement = ibatisPojoElement.getChild(pojoName);
        }
        // String value = element.getText(); <aa>sdfdsfad</aa>
        String value = "";
        if (pojoElement != null) {
            value = pojoElement.getAttributeValue("xmlUrl");
        }
        if ("".equals(value)) {
            return null;
        }
        value = value.trim().replace("#", "\\");
        return value;
    }

    /**
     * 获得根元素
     *
     * @param fileName 用于指定的xml文件名
     * @return
     */
    public Element getRoot(String fileName) {
        // 1.创建解析对象
        // 2.解析对象调用build方法建立文档对象
        // 3.文档对象获得根元素
        SAXBuilder builder = new SAXBuilder(false);
        try {
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            if (cl == null) {
                cl = JdomXML.class.getClassLoader();
            }
            this.url = cl.getResource(fileName);
            // System.out.println(url.getPath());
            if (logger.isDebugEnabled()) {
                logger.debug("JdomPojoXmlUtil子配置文件路径：" + this.url.getFile());
            }
            this.doc = builder.build(this.url);
        } catch (Exception e) {
            logger.error("JdomPojoXmlUtil子配置文件解析错误\t" + fileName + "\t：\r\n" + e);
        }
        Element root = doc.getRootElement();
        return root;
    }

    /**
     * @return
     * @作者：liujiancheng
     * @方法描述：获取主表
     * @创建时间: 2014-8-26 下午12:04:26
     */
    public FieldColumn getMainPojo() {
        if (this.ibatisXmlPath == null)
            return null;
        Element root = getRoot(this.ibatisXmlPath);
        FieldColumn mainPojo = null;
        // 遍历跟元素
        List<?> flist = root.getChildren("Pojos");
        for (int i = 0; i < flist.size(); i++) {
            Element floor = (Element) flist.get(i);
            List<?> Pojolist = floor.getChildren("Pojo");
            for (int j = 0; j < Pojolist.size(); j++) {
                Element room = (Element) Pojolist.get(j);
                String rynMain = room.getAttributeValue("ynMain");
                if (rynMain.equals("1")) {
                    mainPojo = new FieldColumn(room.getAttributeValue("pojo"),
                            room.getAttributeValue("pojoAsName"),
                            room.getAttributeValue("pojoPackage"),
                            room.getAttributeValue("table"),
                            room.getAttributeValue("tableAsName"),
                            room.getAttributeValue("ynMain"));
                    break;
                }
            }
        }
        return mainPojo;

    }

    /**
     * @return
     * @作者：liujiancheng
     * @方法描述：获取子实体类信息 包括子实体类，子表，子表别名
     * @创建时间: 2014-8-26 下午12:04:26
     */
    public ArrayList<FieldColumn> getPojo() {
        if (this.ibatisXmlPath == null)
            return null;
        Element root = getRoot(this.ibatisXmlPath);
        ArrayList<FieldColumn> pojoList = new ArrayList<FieldColumn>();
        // 遍历跟元素
        Element floor = root.getChild("Pojos");
        List<?> Pojolist = floor.getChildren("Pojo");
        for (int j = 0; j < Pojolist.size(); j++) {
            // String pojo,String pojoAsName, String table,String
            // tableAsName,String ynMain
            Element room = (Element) Pojolist.get(j);
            pojoList.add(new FieldColumn(room.getAttributeValue("pojo"), room
                    .getAttributeValue("pojoAsName"), room
                    .getAttributeValue("pojoPackage"), room
                    .getAttributeValue("table"), room
                    .getAttributeValue("tableAsName"), room
                    .getAttributeValue("ynMain")));
        }
        return pojoList;

    }

    /**
     * @param parm null取默认方法getBaseDoctorUserSelectSql的数据 比如如果是parm=1 则取方法
     *             getBaseDoctorUserSelectSql1 的数据
     * @return String
     * "t1.id as baseUserbaseUserid,t1.eu_number as baseUserbaseUsereuNumber,"
     * @方法描述：获取SelectSql
     */
    public String getSelectSql(String parm) {
        if (this.ibatisXmlPath == null)
            return null;
        Element root = getRoot(this.ibatisXmlPath);
        String selectSqlAll = "";
        String selectSql = "";
        // 遍历跟元素
        Element floor = root.getChild("SelectSqls");
        List<?> SelectSqllist = floor.getChildren("SelectSql");
        for (int j = 0; j < SelectSqllist.size(); j++) {
            Element room = (Element) SelectSqllist.get(j);
            String roomParm = room.getAttributeValue("parm");
            if (roomParm.equals("all")) {
                selectSqlAll = room.getAttributeValue("value");
            }
            if (roomParm.equals(parm)) {
                selectSql = room.getAttributeValue("value");
                break;
            }
        }
        if (StringUtils.isBlank(selectSql)) {
            return selectSqlAll;
        } else {
            return selectSql;
        }
    }

    /**
     * @param parm null取默认方法 比如如果是parm=1 则取方法 getBaseDoctorUserSelectSql1 的数据
     * @return String
     * "t1.id as baseUserbaseUserid,t1.eu_number as baseUserbaseUsereuNumber,"
     * @方法描述：获取JoinSql
     */
    public String getJoinSql(String parm) {
        if (this.ibatisXmlPath == null)
            return null;
        Element root = getRoot(this.ibatisXmlPath);
        String joinSqlAll = "";
        String joinSql = "";
        // 遍历跟元素
        Element floor = root.getChild("JoinSqls");
        List<?> JoinSqllist = floor.getChildren("JoinSql");
        for (int j = 0; j < JoinSqllist.size(); j++) {
            Element room = (Element) JoinSqllist.get(j);
            String roomParm = room.getAttributeValue("parm");
            if (roomParm.equals("all")) {
                joinSqlAll = room.getAttributeValue("value");
            }
            if (roomParm.equals(parm)) {
                joinSql = room.getAttributeValue("value");
                break;
            }
        }
        if (StringUtils.isBlank(joinSql)) {
            return joinSqlAll;
        } else {
            return joinSql;
        }

    }

    /**
     * @return
     * @作者：liujiancheng
     * @方法描述：获取子实体类信息 包括子实体类，子表，子表别名
     * @创建时间: 2014-8-26 下午12:04:26
     */
    public ArrayList<FieldColumn> getFieldColumnList() {
        if (this.ibatisXmlPath == null)
            return null;
        Element root = getRoot(this.ibatisXmlPath);
        ArrayList<FieldColumn> list = null;
        // 遍历跟元素
        Element floor = root.getChild("FieldColumns");
        List<?> FieldColumnlist = floor.getChildren("FieldColumn");
        for (int j = 0; j < FieldColumnlist.size(); j++) {
            Element room = (Element) FieldColumnlist.get(j);
            if (list == null)
                list = new ArrayList<FieldColumn>();
            // FieldColumn pojo:实体类名称 field:实体类字段 dateType:数据类型
            // dateTypeShort:数据类型简写 table:表名 column:数据库列 columnComments:数据库列中文注释
            list.add(new FieldColumn(room.getAttributeValue("pojo"), room
                    .getAttributeValue("pojoAsName"), room
                    .getAttributeValue("pojoPackage"), room
                    .getAttributeValue("field"), room
                    .getAttributeValue("dateType"), room
                    .getAttributeValue("dateTypeShort"), room
                    .getAttributeValue("table"), room
                    .getAttributeValue("tableAsName"), room
                    .getAttributeValue("ynMain"), room
                    .getAttributeValue("column"), room
                    .getAttributeValue("columnComments")));
        }
        return list;
    }
}